package com.apache.dict.common;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletResponse;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
import com.thoughtworks.xstream.io.xml.XmlFriendlyNameCoder;

/**
 * Xstream工具类
 * @author lvcai
 *
 */
public class XmlUtil {
	private static final String xmlStart = "<xml-body>\n<Head></Head>\n<Body>\n";
	private static final String xmlEnd = "\n</Body>\n</xml-body>";
	private static XStream xstream;
	static {
		xstream = new XStream(new DomDriver("UTF-8", new XmlFriendlyNameCoder("-_", "_")));
		//xstream = new XStream();
	}

	private static String xmlHead = "<?xml version='1.0' encoding='UTF-8'?>\n";

	/**
	 * java 转换成xml
	 * @Title: toXml 
	 * @Description: TODO 
	 * @param obj 对象实例
	 * @return String xml字符串
	 */
	public static String toXml(Object obj) {
		//XStream xstream=new XStream();
		//		XStream xstream=new XStream(new DomDriver()); //直接用jaxp dom来解释
		//		XStream xstream=new XStream(new DomDriver("utf-8")); //指定编码解析器,直接用jaxp dom来解释

		////如果没有这句，xml中的根元素会是<包.类名>；或者说：注解根本就没生效，所以的元素名就是类的属性
		xstream.processAnnotations(obj.getClass()); //通过注解方式的，一定要有这句话
		return xmlHead + xstream.toXML(obj);
	}

	/**
	 *  将传入xml文本转换成Java对象
	 * @Title: toBean 
	 * @Description: TODO 
	 * @param xmlStr
	 * @param cls  xml对应的class类
	 * @return T   xml对应的class类的实例对象
	 * 
	 * 调用的方法实例：PersonBean person=XmlUtil.toBean(xmlStr, PersonBean.class);
	 */
	public static <T> T toBean(String xmlStr, Class<T> cls) {
		xmlStr = xmlStr.trim();
		xmlStr = xmlStr.replaceAll(xmlStart, "");
		xmlStr = xmlStr.replaceAll(xmlEnd, "");
		xstream.alias(cls.getSimpleName(), cls);
		xstream.processAnnotations(cls);
		T obj = (T) xstream.fromXML(xmlStr);
		return obj;
	}

	/**
	 * 输出客户端信息
	 * @param xml
	 * @param response
	 */
	public static void outputXml(String xml, HttpServletResponse response) {
		try {
			response.setContentType("text/xml; charset=UTF-8");
			PrintWriter out = response.getWriter();
			out.print(xml);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
